package com.ly.hotel.common;

import com.ly.hotel.board.SerialPortHandler;
import com.ly.hotel.board.SerialPortHandler2;

import android.app.Dialog;
import android.content.Intent;
import android.os.Build;
import android.util.Log;

public abstract class HandNoBinder   {
//	private OnCompleteHandler completeHandler;
	public static SerialPortHandler sp = null;
	public static SerialPortHandler2 sp2 = null;
	

	public HandNoBinder() {
	}
	
//	public void setCompleteHandler(OnCompleteHandler c) {
//		completeHandler = c;
//	}

	public  void bind() {
		initSerialPort();
	}
	
	public void unbind() {
		closeSerialPort();
	}
		
	private void closeSerialPort() {
		
		if(Build.BOARD.endsWith(Constants.BOARD_TYPE_ADA628_NAME)){
			if (sp != null) {
				try {
					sp.close();
					sp = null;
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		} else {
			
			if (sp2 != null) {
				try {
					sp2.close();
					sp2 =null;
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}

		
	}
	
	private void initSerialPort() {
		if(Build.BOARD.endsWith(Constants.BOARD_TYPE_ADA628_NAME)){
			sp = new SerialPortHandler(){
	
				@Override
				public void onInputComplete(String id) {
					System.out.println("HandNoBinder->rev手牌号:" + id);  
					MyApplication.setBandNo(id);
			        String ACTION = "com.ly.broadcast.HandnoReceiver"; 
					Intent intent = new Intent();
			        intent.setAction(ACTION);
			        intent.putExtra("handno", id);
			        MyApplication.getContext().sendBroadcast(intent);
				}
				
			};
			try {
				if(sp != null && sp.deviceExist()){
					sp.open();
				}else{
					sp = null;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			sp2  = new SerialPortHandler2(){
	
				@Override
				public void onInputComplete(String id ) {
					System.out.println("HandNoBinder->rev 手牌号:" + id);  
			        String ACTION = "com.ly.broadcast.HandnoReceiver"; 
					Intent intent = new Intent();
			        intent.setAction(ACTION);
			        intent.putExtra("handno", id);
			        MyApplication.getContext().sendBroadcast(intent);
					MyApplication.setBandNo(id);
				}
				
			};
			try {
				if(sp2 != null && sp2.deviceExist()){
					sp2.open();
				}else{
					sp2 = null;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		Log.i("serial", "sp=" + sp + ",sp2=" + sp2);
	}
	
	public interface OnCompleteHandler {
		public void onComplete(String id, Dialog dialog);
	}
	
	public interface OnDialogClose {
		public void close();
	}
}


